import tornado.web
import tornado.ioloop
import json
from config.db import db

# 开启debug模式
settings = {'debug': True}


class BaseHandler(tornado.web.RequestHandler):
    # 重写该方法
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")  # 允许所有的域名访问
        self.set_header("Access-Control-Allow-Headers", "*")  # 允许携带所有的参数
        self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")  # 允许所有的请求方式
        self.set_header("Access-Control-Max-Age", "3600")  # 允许连接时，最大响应时间

    # 定义一个响应的方法，不需要实现什么功能
    def options(self):
        pass


#创建类
class AddComputer(BaseHandler):
    def post(self):
        name = self.get_query_argument("name")
        price = self.get_query_argument("price")
        processor = self.get_query_argument("processor")
        size = self.get_query_argument("size")
        kind_id = self.get_query_argument("kind_id")
        sql = "insert into computer(name,price,processor,size,kind_id) values ('%s','%s','%s','%s','%d') "%(name,price,processor,size,int(kind_id))
        db.add(sql)
        db.commit()
        self.finish({"code": 200})

    def get(self):
        page = self.get_query_argument("page")
        page_size = self.get_query_argument("page_size")
        start = (int(page) - 1) * int(page_size)
        sql = "select * from computer limit %d,%d" % ((int(start), int(page_size)))
        res = db.findAll(sql)
        sql1 = "select count(id) as a from computer"
        res1 = db.findone(sql1)
        total = int(res1["a"])
        for i in res:
            i["price"] = float(i["price"])
        self.finish({"code": 200,"data": res,"total": total})

class GetKind(BaseHandler):
    def get(self):
        sql = "select * from kind"
        res = db.findAll(sql)
        self.finish({"data": res})

class GetComputer(BaseHandler):
    def get(self):
        id = self.get_query_argument("id")
        sql = "select * from computer where kind_id=%d" % int(id)
        res = db.findAll(sql)
        for i in res:
            i["price"] = float(i["price"])
        self.finish({"data": res})

app = tornado.web.Application([
    (r"/addcomputer", AddComputer),
    (r"/getkind", GetKind),
    (r"/getcomputer", GetComputer),
], **settings)

if __name__ == "__main__":
    app.listen(8000)
    print("server start")
    tornado.ioloop.IOLoop.current().start()


